package com.z.system.controller;

import java.util.List;
import java.util.UUID;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.z.system.model.Permission;
import com.z.system.service.PermissionService;
import com.z.system.utils.R;
import com.z.system.vo.Menu;
import com.z.system.vo.MenuRequestVo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

/**
 * 权限控制器
 */
@RestController
@RequestMapping("/api/permission")
@Tag(name = "权限管理", description = "权限相关接口")
public class PermissionController {
    private final PermissionService permissionService;

    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    /**
     * 获取所有权限列表
     * 返回与getMenuList相同格式的Menu对象列表，便于前端处理
     */
    @GetMapping("/list")
    @PreAuthorize("hasAuthority('sys:menu:view')")
    @Operation(summary = "获取所有权限", description = "获取系统中所有的权限，返回前端友好的菜单树结构")
    public R<List<Menu>> getAllPermissions() {
        List<Menu> menus = permissionService.getAllPermissionsAsMenuTree();
        return R.success(menus);
    }

    /**
     * 添加菜单
     * 支持完整的前端菜单配置参数
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('sys:menu:create')")
    @Operation(summary = "添加菜单", description = "添加新的菜单，支持完整的前端菜单配置参数")
    public R<Permission> addMenu(@RequestBody MenuRequestVo menuRequest) {
        Permission permission = menuRequest.toPermission();
        java.util.Date now = new java.util.Date();
        permission.setCreateTime(now);
        permissionService.savePermission(permission);
        return R.success();
    }

    /**
     * 更新或添加菜单
     * 支持处理前端传来的id为0（表示新增）的情况，完全兼容前端传参格式
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    @Operation(summary = "更新或添加菜单", description = "根据ID更新菜单信息，如果ID为0或无效则新增菜单，支持完整的前端菜单配置参数")
    public R<Permission> updateMenu(@RequestBody MenuRequestVo menuRequest) {

        // 使用toPermission方法创建新的权限对象
        Permission permission = menuRequest.toPermission();

        // 使用getIdAsUUID()方法获取UUID类型的id
        Permission existingPermission = permissionService.getPermissionById(menuRequest.getIdAsUUID());
        if (existingPermission == null) {
            return R.error("权限不存在");
        }

        // 确保ID一致
        permission.setId(existingPermission.getId());
        permission.setCreateTime(existingPermission.getCreateTime()); // 保留创建时间
        permission.setCreateId(existingPermission.getCreateId()); // 保留创建人
        permissionService.updatePermission(permission);

        return R.success();
    }

    /**
     * 删除菜单
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @Operation(summary = "删除菜单", description = "根据ID删除菜单")
    public R<Boolean> deleteMenu(@PathVariable UUID id) {
        permissionService.deletePermission(id);
        return R.success(true);
    }

    /**
     * 添加权限按钮
     */
    @PostMapping("/auth/add")
    @PreAuthorize("hasAuthority('sys:menu:create')")
    @Operation(summary = "添加权限按钮", description = "添加新的权限按钮")
    public R<Permission> addAuthButton(@RequestBody Permission permission) {
        permission.setType(2);
        Permission savedPermission = permissionService.savePermission(permission);
        return R.success(savedPermission);
    }

    /**
     * 更新权限按钮
     */
    @PostMapping("/auth/update")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    @Operation(summary = "更新权限按钮", description = "更新权限按钮信息")
    public R<Permission> updateAuthButton(@RequestBody Permission permission) {
        Permission updatedPermission = permissionService.updatePermission(permission);
        return R.success(updatedPermission);
    }

    /**
     * 删除权限按钮
     */
    @PostMapping("/auth/delete/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    @Operation(summary = "删除权限按钮", description = "根据ID删除权限按钮")
    public R<Boolean> deleteAuthButton(@PathVariable UUID id) {
        permissionService.deletePermission(id);
        return R.success(true);
    }
}